#ifndef _XTHREAD_SEMA_H
#define _XTHREAD_SEMA_H

#include "inneral/list.h"
#include "xthread-spinlock.h"
#include "xthread-mutex.h"
#include "xthread-waitqueue.h"
#include <sys/time.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
	int counter;	    // 统计资源的原子变量
    xthread_mutex_t lock;       // 维护信号量资源的锁
	xthread_wait_queue_t waiters;	// 在此信号量上等待的进程
} xthread_sema_t;


static inline void xthread_sema_init(xthread_sema_t *sema, int value)
{
	sema->counter = value;
    xthread_mutex_init(&sema->lock);
	xthread_wait_queue_init(&sema->waiters);
}

static inline void xthread_sema_destroy(xthread_sema_t *sema)
{
    xthread_mutex_unlock(&sema->lock);
    if (sema->counter > 0)
        xthread_wait_queue_wakeup_all(&sema->waiters);
    sema->counter = 0;
}

int xthread_sema_wait_timeout(xthread_sema_t *sema, struct timeval *tv);
void xthread_sema_wait(xthread_sema_t *sema);
int xthread_sema_try_wait(xthread_sema_t *sema);
void xthread_sema_post(xthread_sema_t *sema);
int xthread_sema_getvalue(xthread_sema_t *sema, int *sval);

#ifdef __cplusplus
}
#endif

#endif /* _XTHREAD_SEMA_H */